<template>
	<div>
		<div class="header">




			<van-nav-bar style="  background: linear-gradient(90deg, #41A9B7,#4fd4e2, #41A9B7);height: 5rem;line-height: 5rem;">

				<span class="title" slot="title">灯效管理</span>

				<span style="font-size: 1.5625rem ; color: white; font-weight: 500;" slot="right">
					<van-button type="primary" color="#348994" @click="back">&nbsp;返&nbsp;&nbsp;&nbsp;回&nbsp;</van-button>
				</span>


				<!-- <span style="font-size: 25px ; color: white; font-weight: 500;" slot="left">
					<van-button type="primary" color="#FF7C00" @click="exit_show=true">&nbsp;退&nbsp;&nbsp;&nbsp;出&nbsp;</van-button>
				</span> -->
			</van-nav-bar>
			<!-- <van-nav-bar title="智能供佛系统" style=" background: url(./images/系统标题部分.png);height: 80px;line-height: 80px; background-size:1142px 80px;background-repeat:no-repeat;">
				<van-icon name="search" slot="right" />
			</van-nav-bar> -->
		</div>





		<!-- /////////////////////////////////////////////////////////// -->
		<div id="content" class="content" >

			<!-- 选择弹出层 -->







			<!-- <van-popup v-model="showPicker" position="top">
				
			</van-popup> -->
			<!-- 选择过滤器  -->
			<div id="preSelect" style=" height: 3.4375rem;	margin-top:20px;		line-height: 3.4375rem;; font-size: 20px;color: wheat; font-weight: bold; width:98% ;">
				<van-row gutter="2">


					<van-col style="margin-left: 2%;" span="2"> <span>追思间：</span></van-col>

					<van-col span="3">
						<el-select v-model="room" placeholder="选择宫殿" @change="changeRoom">
							<el-option v-for="item in options0" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>

					</van-col>

					<van-col span="2">

						<el-select v-model="tier" placeholder="选择分区" @change="changeTier">
							<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</van-col>


					<van-col span="16"> <span>操作选项：</span>

						<van-button @click="choose_on()" color="#FFAE00" type="primary">点亮已选</van-button>




						<van-button @click="choose_off()" color="#FFAE00" style="margin-left: 10px;" type="primary">重置当前区域</van-button>

						<van-button @click="all_on()" color="#FFAE00" style="margin-left: 10px;" type="primary">全亮</van-button>
						<van-button @click="all_off()" color="#FFAE00" style="margin-left: 10px;" type="primary">全灭</van-button>


						<van-button @click="all_restore()" style="margin-left: 10px;" type="primary">全部恢复</van-button>

						<van-button @click="ledStyle(3)" color="#FFAE00" style="margin-left: 10px;" type="primary">跑马灯效</van-button>

						<van-button       v-show="bcShow"    @click="ledStyle(4)" color="#FFAE00" style="margin-left: 10px;" type="primary">呼吸灯效</van-button>
					</van-col>




					<!-- 	<van-col span="2"> <span>已供：{{ispriceCount}}</span></van-col>
					<van-col span="2"> <span>待供：{{totalCount-ispriceCount}}</span></van-col> -->




					<!-- <van-col span="2"> <span>应付金额：</span></van-col> -->


					<!-- <el-button type="primary" disabled>返回</el-button> -->



					<!-- <van-col span="3">
						<van-button size="large" style="width: 100px;" color="#CC4117">退出</van-button>
					</van-col> -->
				</van-row>

			</div>

		<!-- background: #e59336;  #348994 -->	
			<div style="height: 31.25rem;  width: 96%; margin-left: 2%; border: solid #e59336; background: #2f878d; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);  border-radius: 5px; padding: 5px;">
				<!--  -->

				<!--  选择区域	-->
				<!-- li一个v-for ，里面内容img在一个v-for-->
				<div class="select" style="  overflow: auto; height: 100%; white-space: nowrap;">
					<van-loading type="spinner" color="#1989fa" size="80px" v-if="load" style="margin-top: 12.5rem;" />

					<ul v-else  v-show="domShow">
						<li v-for="led_row in ledList" style="margin-top: 0rem;margin-bottom: -0.5rem;">

							<div v-for="led,key in led_row" style="	position: relative;	display: inline-block; ">

								<van-image width="4rem" height="4rem" fit="cover" :src="(led.state==5?images[3]:(led.isbright?images[2]:(led.ifchoose?images[1]:images[0])))"
								 @click="choose(led)" style="margin :0.5rem;" />
<span 
								style="display: block;	font-size: 0.7rem; color: #dfbd7a;  position: absolute; left: 0;  right: 0; bottom: 0.79rem;  margin: auto;	text-align: center;	z-index: 10;">{{led.code}}</span>
								<!-- <span style="font-size: 0.7rem; color: #df8f81; position: absolute; left: -3rem;bottom: 0.85rem;	text-align: center;	z-index: 10;">{{led.code}}</span> -->
							</div>
						</li>

					</ul>
				</div>
			</div>

			<!-- /////////////// -->


			<div style="text-align: right; margin-right: 2rem;margin-top: 0.5rem;">
				<el-color-picker v-model="color" @change="colorChange(color)" @active-change="doMess($event)" :show-alpha="false"
				 color-format="rgb" :predefine="predefineColors">
				</el-color-picker>
			</div>
			
			


			<div style=" display: none;">
				{{chooseLedList}}<!-- 不加不行，影响页面运行效果，巨特么奇怪 -->
			</div>







			<van-dialog v-model="exit_show" title="退出界面" show-cancel-button @confirm="exit()" @cancel="exit_show=false" style="width: 30rem;">

				<span style="font-size: 0.8rem;color: firebrick;">是否要退出当界面程序？（此操作一般用于程序调试）</span>
			</van-dialog>




			<!-- 	<div class="ledList">



			</div> -->




		</div>
		<!-- /////////////////////////////////////////////////////////// -->
	</div>

</template>

<script>
	export default {


		data() {
			return {
				bcShow:false,
				topicList:[],
				domShow:false,
				topic: "100_1",
				exit_show: false,
				totalFee: 0,

				price: 0, //单价
				//[{"title":"大宝殿","create_time":1559266057735,"tid":1,"where":"东边","id":0},{"title":"承德殿","create_time":1559266922188,"tid":1,"where":"西边","id":1}]

				totalCount: 0,
				ispriceCount: 0,
				options: [{
					value: '0',
					label: 'A区'
				}, {
					value: '1',
					label: 'B区'
				}, {
					value: '2',
					label: 'C区'
				}, {
					value: '3',
					label: 'D区'
				}, {
					value: '4',
					label: 'E区'
				}],
				tier: '0',

				options0: [{
					value: '0',
					label: '大雄宝殿'
				}, {
					value: '1',
					label: '观音阁'
				}],
				room: '0',

				options2: [{
					value: '0',
					label: '一天'
				}, {
					value: '1',
					label: '一周'
				}],
				durationTime: '0',

				show: '',
				value: '',
				showPicker: false,
				chooseLedList: [],

				ledList: [{ //按row分组
					ifchoose: 0,
					name: "长明灯A1"
				}],
				templeData: null,
				priceData: {},
				//图片1，无状态，2选中，3已售
				images: ["./images/foxiangguan.png", "./images/choosed.png", "./images/foxiang.png", "./images/tianchontu.jpg"],
				load: true,
				color: 'rgb(255,255,255)',
				predefineColors: [
					'rgb(0, 0, 0)',
					'rgb(255,255, 255)',
					'rgb(128,128, 128)',

					'rgb(128,0, 0)',
					'rgb(0,128, 0)',
					'rgb(0,0, 128)',
					'rgb(128,128, 0)',
					'rgb(0,128, 128)',

					'#ff4500',
					'#ff8c00',
					'#ffd700',
					'#90ee90',
					'#00ced1',
					'#1e90ff',
					'#c71585',
					'rgb(255, 69, 0)',
					'rgb(255, 120, 0)'

				],


				client: null


			}
		},
		filters: {


			//[{"title":"一天","create_time":1545960786279,"tid":null,"day":1,"price":0.01},{"title":"一个月","create_time":1545960801124,"tid":null,"day":30,"price":60},{"title":"半年","create_time":1545960818376,"tid":null,"day":180,"price":180},{"title":"一年","create_time":1545960830201,"tid":null,"day":365,"price":365}]
			//过滤数据用作显示
			ledName(value) {

				let str = "";
				for (let i = 0; i < value.length; i++) {

					if (i == value.length - 1) {

						str = str + value[i].code;

					} else {
						str = str + value[i].code + ","

					}
				}

				if (str.length > 20) {
					str = str.substring(0, 20) + "....";
				}


				return str;
			}

		},
		methods: {

			colorChange(value) {



				let color = value.replace("rgb(", "").replace(")", "").split(",");

				//浏览器可以直接操作，但是这里因为是低频确认操作，可保留
				this.axios.post('https://mianmianshi.com/cms/temple/client/updateLed', {
						where: {
							'tid': this.$store.getters.getTid || localStorage.tid,
							
						},
						update: {
							R: color[0],
							G: color[1],
							B: color[2]
						}
					})
					.then((res) => {
						if (res.data > 0) {
							this.ledShow();
							//this.getLedList();
						}
					})
					.catch((err) => {
						console.log("失败了");
						console.log(err)
					});

			},




			exit() {
				this.axios.get('http://localhost:8088/gui_exit')
					.then((res) => {

					})
					.catch((err) => {
						console.log("失败了");
						console.log(err)
					});


				/* this.$dialog.confirm({
				  title: '退出界面程序',
				  message: '是否要退出当界面程序？（此操作一般用于程序调试）',
				  className:'exit'
				}).then(() => {
					
				
						
				  // on confirm
				}).catch(() => {
				  // on cancel
				}); */





			},


			//全灭
			all_off() {
				this.axios.post('https://mianmianshi.com/cms/temple/admin/AllPutOut', {
						'tid': this.$store.getters.getTid
					})
					.then((res) => {

						this.chooseLedList = [];

						this.getLedList();

						this.$toast.success({
							message: '已全部熄灭！'

						});


						////
						this.ledShow();
						////


					})
					.catch(function(error) {

						console.log(error);
					});
			},


			ledShow() {
				this.axios.post(this.$config.doMqttUrl+'/led/ledShow', {
						'tid':  parseInt(this.$store.getters.getTid || localStorage.tid)
					})
					.then((res) => {

						this.$totast.success("ok");


					})
					.catch(function(error) {

						console.log(error);
					});
			}

			,

			all_on() {

				this.axios.post('https://mianmianshi.com/cms/temple/admin/fullBright', {
						'tid': this.$store.getters.getTid||localStorage.tid
					})
					.then((res) => {
						this.getLedList();


						this.$toast.success({
							message: '已全部点亮！'
						});


						////
						this.ledShow();
						////

					})
					.catch(function(error) {

						console.log(error);
					});
			},
			/* 全部恢复 */
			all_restore() {

				this.axios.post('https://mianmianshi.com/cms/temple/admin/restore', {
						'tid': this.$store.getters.getTid||localStorage.tid
					})
					.then((res) => {
						this.chooseLedList = [];
						this.getLedList();
						this.$toast.success({
							message: '已全部复原！'

						});

						////
						this.ledShow();
						////

					})
					.catch(function(error) {

						console.log(error);
					});
			},

			/* 点亮已选 */
			choose_on() {

				if (!this.chooseLedList.length) {
					this.$toast.fail({
						message: '请选择！'

					});
					return;
				}

				this.axios.post('https://mianmianshi.com/cms/temple/admin/wordGenerator', {
						'ledList': this.chooseLedList
					})
					.then((res) => {

						this.chooseLedList = [];
						this.getLedList();
						this.$toast.success({
							message: '已点亮！'

						});

						////
						this.ledShow();
						////

					})
					.catch(function(error) {

						console.log(error);
					});
			},

			/* 熄灭当前，方便重写 */
			choose_off() {

				this.axios.post('https://mianmianshi.com/cms/temple/admin/chooseOff', {
						'tid': this.$store.getters.getTid ||localStorage.tid,
						'tier': this.tier,
						'room': this.room
					})
					.then((res) => {
						this.chooseLedList = [];
						this.getLedList();
						
						this.ledShow();
						this.$toast.success({
							message: '当前区域已熄灭！'

						});
					})
					.catch(function(error) {
						
						

						console.log(error);
					});
			},


			ledStyle(n) {
				this.axios.post(this.$config.doMqttUrl+'/led/ledStyle', {
						'tid': this.$store.getters.getTid || localStorage.tid,
						'led_style': n

					})
					.then((res) => {

						let mes = '';
						if (n == 3) {
							mes = '跑马灯效！';
						} else if (n == 4) {
							mes = '呼吸灯效！';
						}

						this.$toast.success({
							message: mes
						});

					})
					.catch(function(error) {
						console.log(error);
					});


				this.axios.post('https://mianmianshi.com/cms/temple/admin/paoma', {
						'tid': this.$store.getters.getTid || localStorage.tid,
						'led_style': n

					})
					.then((res) => {

						let mes = '';
						if (n == 1) {
							mes = '跑马灯效！';
						} else if (n == 2) {
							mes = '呼吸灯效！';
						}

						this.$toast.success({
							message: mes

						});

					})
					.catch(function(error) {

						console.log(error);
					});

			},

			toGongfoStep1() {
				//判断用户是否选择佛龛
				if (this.chooseLedList.length) {
					this.$router.push({
						path: '/GongfoStep1',
						query: {
							total_fee: this.totalFee,
							ledList: this.chooseLedList,
							day: this.durationTime
						}
					});
				} else {
					this.$toast.fail("请先选择要供奉的佛龛")
				}

			},

			changeRoom() {
				let options = [];
				let data = JSON.parse(this.templeData.tierlist);
				for (let i = 0; i < data.length; i++) {
					if (data[i].where == this.room) {
						options.push({
							value: data[i].id,
							label: data[i].title
						})
					}

				}
				console.log("options0=================", options)
				this.options = options;
				this.tier = this.options[0].value;
				console.log("this.tier=================", this.tier)
				this.getLedList();
			},
			changeTier() {
				this.getLedList();


			},
			changeDurationTime() {

				//console.log(this.options2)

				//重新定价
				for (let i = 0; i < this.options2.length; i++) {
					//	console.log(parseFloat(this.options2[i].price).toFixed(2))

					if (this.options2[i].value == this.durationTime) {
						this.price = parseFloat(this.options2[i].price).toFixed(2);

						console.log(this.price);
						break;
					}
				}

				//重新计算价格
				this.totalFee = this.price * this.chooseLedList.length;
			},

			pikerChange(value) {
				console.log(value);
				//this.value = value;
				this.showPicker = false;
			},
			getContainer() {
				return document.querySelector('.content');
			},

			onConfirm(value) {
				console.log('confirm:', value);
				this.value = value;
				this.showPicker = false;
			},

			choose(led) {

				if (led.isbright || (led.state == 5)) {
					//无效选择
				} else {


					//更新选择状态
					if (led.ifchoose) {
						console.log("取消选了一个！")
						led.ifchoose = 0;
						for (let i = 0; i < this.chooseLedList.length; i++) {

							if (led.id == this.chooseLedList[i].id) {
								this.chooseLedList.splice(i, 1);
							}
						}

					} else {
						console.log("选了一个！")
						led.ifchoose = 1;
						this.chooseLedList.push({
							id: led.id,
							code: led.code
						});

					}

					//重新计算价格
					this.totalFee = this.price * this.chooseLedList.length;
				}




			},

			getLedList() {
				this.load=true;
				this.domShow = false;
				//获取led按行数据
				this.axios.post('https://mianmianshi.com/cms/temple/user/led', {
						room: this.room,
						tier: this.tier,
						tid: this.$store.getters.getTid||localStorage.tid

					})
					.then((res) => {
						console.log("res->", res);
						this.ledList = res.data.data.data;
						console.log("ledList->", this.ledList);
						this.doLedList();
						
						this.load = false;
						this.$nextTick(() => {
							setTimeout(() => {
								this.domShow = true;
							}, 100)
						
						});
					})
					.catch(function(error) {
						//this.mes = "未找到该用户，请检查是否输入错误";
						console.log(error);
					});

				//获取led数据

				/* 
								this.axios.post('https://mianmianshi.com/cms/temple/client/ispriceCount', {
										where: {
											tid: this.$store.getters.getTid
										}
									})
									.then((res) => {
										console.log("res->", res);

										console.log("ledcount->", res.data);

										this.totalCount = res.data.totalCount;
										this.ispriceCount = res.data.ispriceCount;
									})
									.catch(function(error) {
										//this.mes = "未找到该用户，请检查是否输入错误";
										console.log(error);
									}); */

			},
			
			
			getTopic(){
				this.axios.get(this.$config.doMqttUrl+'/led/getTopics', {
						params:{
							tid:localStorage.tid
						}
					
				
					})
					.then((res) => {
					this.topicList=res.data;
					})
					.catch(function(error) {
						//this.mes = "未找到该用户，请检查是否输入错误";
						console.log(error);
					});
			},

			doLedList() {
				let tem_ledList = this.ledList; //遍历中途改变数组状态可能会导致指针异常
				let tc = {
					state: 5
				}; //填充数据

				for (let e = 0; e < tem_ledList.length; e++) {
					////

					////先检查头一个是不是空着的
					let first_gap = tem_ledList[e][0].column - 1;
					for (let i = 0; i < first_gap; i++) {
						this.ledList[e].splice(i, 0, tc);
					}
					for (let i = 0; i < tem_ledList[e].length; i++) {
						if (i + 1 < tem_ledList[e].length) {
							let gap = tem_ledList[e][i + 1].column - tem_ledList[e][i].column;
							if (gap > 1) {
								for (let j = i + 1; j < gap + i; j++) {
									this.ledList[e].splice(j, 0, tc); //这个函数省了一堆代码
								}
							}
						}

					}
					//////
				}
			},

			initData() {



				let tempInterval = setInterval(() => {

					console.log("数据获取中....");
					if (this.templeData != null) {
						clearInterval(tempInterval);
						console.log(this.templeData);

						///////////////////


						console.log("初始化数据。。。。。。。。。。");

						//宫殿room
						let data0 = JSON.parse(this.templeData.addresslist);
						console.log("data0=====================", data0);
						let options0 = [];
						for (let i = 0; i < data0.length; i++) {
							options0.push({
								value: data0[i].id,
								label: data0[i].title
							})
						}
						console.log("options0=================", options0)
						this.options0 = options0;
						this.room = 0;


						//殿内分区
						let data = JSON.parse(this.templeData.tierlist);
						console.log("data0=====================", data0);
						let options = [];
						for (let i = 0; i < data.length; i++) {
							if (data[i].where == this.room) {
								options.push({
									value: data[i].id,
									label: data[i].title
								})
							}
						}
						console.log("options0=================", options)
						this.options = options;
						this.tier = 0;

						//供灯时长
						let data2 = JSON.parse(this.templeData.led_price);
						console.log("data0=====================", data2);
						let options2 = [];
						for (let i = 0; i < data2.length; i++) {
							options2.push({
								value: data2[i].day,
								label: data2[i].title,
								price: data2[i].price
							}, )
						}
						console.log("options0=================", options)
						this.options2 = options2;
						this.durationTime = this.options2[0].value;

						//初始化价格
						for (let i = 0; i < this.options2.length; i++) {
							//	console.log(parseFloat(this.options2[i].price).toFixed(2))

							if (this.options2[i].value == this.durationTime) {
								this.price = parseFloat(this.options2[i].price).toFixed(2);
								console.log(this.price);
								break;
							}
						}



						//////////////////

					} else {

						if (this.$store.getters.getTempleData) {
							//
							this.templeData = this.$store.getters.getTempleData;
						} else {
							this.templeData = localStorage.getItem("templeData");
						}
					}


				}, 300);





				//

			},
			back() {
				//this.$router.push("/");
				this.$router.go(-1);
			}

			,

			doMess(value) {

				if (this.client.isConnected()) {
					let color = value.replace("rgb(", "").replace(")", "").split(",");
					//
					let array = new ArrayBuffer(4);
					let bytes = new Int8Array(array);
					bytes[0] = color[0];
					bytes[1] = color[1];
					bytes[2] = color[2];
					bytes[3] = 5;
					//
					let message = new Paho.Message(bytes);
					
					let tid=localStorage.tid;
					
					
					for (let i = 0; i < this.topicList.length; i++) {
						
						message.destinationName =tid+"_"+this.topicList[i];
						this.client.send(message);
					}
					
					
				
					
					
				} else {
					this.mqtt_begin();
					console.log("连接异常！1秒后尝试自动连接");
				}
			},
			mqtt_begin() {
				// Create a client instance

				let location = {
					//hostname: '129.211.90.180',
					hostname: '47.100.188.31',
					port: 1884
				};
				let topic = this.topic;
				
				
				
				let current_id=localStorage.tid+"_"+ new Date().getTime();
				let client = new Paho.Client(location.hostname, Number(location.port),current_id);
				// set callback handlers
				client.onConnectionLost = onConnectionLost;
				client.onMessageArrived = onMessageArrived;

				// connect the client
				client.connect({
					onSuccess: onConnect
					,useSSL:true,
					//hosts:["wss://xf.mianmianshi.com:1885/mqttSSL"]
					
					
				});
				// called when the client connects
				function onConnect() {
					// Once a connection has been made, make a subscription and send a message.
					console.log("onConnect");
					/* client.subscribe(topic);
					let message = new Paho.Message("hello");
					message.destinationName = topic;
					client.send(message); */
				}

				// called when the client loses its connection
				function onConnectionLost(responseObject) {
					if (responseObject.errorCode !== 0) {
						console.log("onConnectionLost:" + responseObject.errorMessage);
					}
				}

				// called when a message arrives
				function onMessageArrived(message) {
					console.log("onMessageArrived 字符串:" + message.payloadString);
					console.log("onMessageArrived 字节:" + message.payloadBytes);
				}

				this.client = client;
			}


		},

		created() {
			//获取tid
			
			
		/* 	
			var newUrl = "http://localhost:8080/#/adminPageLed?tid=100";
			history.pushState(null,null,newUrl); */
			
			

			if (localStorage.tid) {
				this.$store.commit("setTid", localStorage.tid);
				
				this.topic = localStorage.tid+"_"+1;
			}
			
			console.log(this.$route);


		    this.getTopic();

			this.getLedList();

			this.initData();


			this.mqtt_begin();
			
			
			








		},
		mounted() {

		},
		watch: {
			/* color(){
				alert(this.color);
				this.colorChange(this.color);
			} */

		}

	}
</script>

<style>
	.xundeng {
		position: absolute;
		height: 100%;
		width: 100%;
		background: url(../../public/images/xundeng.png) no-repeat;
		background-size: 100% 100%;
	}

	/* 
 
消除滚动条，牛逼 
 */
	.select::-webkit-scrollbar {
		display: none
	}




		{
		/* scrollbar-3dlight-color: #fff; // 3d亮色阴影边框(threedlightshadow)的外观颜色 */
		/* scrollbar-highlight-color: #fff; // 滚动条3d高亮边框(threedhighlight)的外观颜色
		scrollbar-arrow-color: #fff; // 滚动条方向箭头的颜色
		scrollbar-shadow-color: #fff; // 滚动条方向箭头的颜色
		scrollbar-darkshadow-color: #fff; // 滚动条3d暗色阴影边框(threeddarkshadow)的外观颜色
		scrollbar-base-color: #fff; // 滚动条基准颜色
		scrollbar-track-color: #fff; // 滚动条拖动区域的外观颜色 */
	}

	ul li {}


	.exit {
		background: red;


		width: 100px;
	}



	.gf {
		/* border: solid 1px;
		width: 100%;
		 position: absolute;
		    top: 0px;
		    bottom: 0px; */
	}
</style>
